<?php
/**
 * Created by 无所谓已
 * User: Administrator
 * Date: 2025-08-22
 * Time: 22:31
 */

namespace plugin\csauto\app\process;


use plugin\csauto\app\model\TorrentTaskModel;
use plugin\csauto\app\service\downloader\DownloaderWorkService;
use support\Log;
use Workerman\Crontab\Crontab;
use Workerman\Timer;

/**
 * Class TaskAssignPublishingProcess
 * 步骤6
 * 对于已经准备完成的任务进行子站点的分发
 *
 * @package plugin\csauto\app\process
 */
class TaskAssignPublishingProcess
{
    // 定时器句柄/ID
    protected $timer;
    protected $wechatTimer;
    protected $torrentTaskMaxNum = 2;

    // 时间间隔 (单位: 秒, 默认5秒)
    protected $interval = 15;

    public function onWorkerStart()
    {
        if(getenv('WORK_DEBUG')) return true;
        $this->timer = Timer::add($this->interval, function () {
            try {
                // 这里执行系统预设的定时任务事件
                $this->run();
            } catch (\Throwable $e) {
                echo 'ERROR[TaskAssignPublishingProcess]: ' . $e->getMessage() . PHP_EOL;
            }
        });

        return true;
    }

    public function run()
    {
        addlog('任务-分配发布任务', 'start');
        /*检查未完成的任务情况*/
        foreach (TorrentTaskModel::where('status', 1)->where('down_status', 2)->where('mediaInfo_status', 2)->get() as $item) {
            DownloaderWorkService::assignPublishingTasks($item);
        }
        return '任务调用：' . date('Y-m-d H:i:s') . "\n";
    }

    /**
     * 停止/删除定时器
     *
     * @return bool
     */
    public function stop()
    {
        return Timer::del($this->timer);
    }

}